package com.opdar.athena.support.base;

import com.opdar.athena.support.entities.UserEntity;
import com.opdar.platform.core.base.Context;
import com.opdar.platform.core.base.Interceptor;
import com.opdar.platform.core.session.ISessionManager;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import java.io.IOException;

/**
 * Created by shiju on 2017/1/24.
 */
public class ClientViewInterceptor implements Interceptor,ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public boolean before() {
        Context.getResponse().setCharacterEncoding("UTF-8");
        String token = (String) Context.getRequest().getSession().getAttribute("token");
        if(Context.getRequest().getParameterMap().containsKey("token")){
            token = Context.getRequest().getParameter("token");
        }
        if(token != null){
            ISessionManager sessionManager = applicationContext.getBean(ISessionManager.class);
            Object user = sessionManager.get(token);
            if(user != null){
                if(user instanceof UserEntity){
                    sessionManager.clearTimeout(token);
                    Context.putAttribute("user",user);
                    return true;
                }
            }
        }
        try {
            String appId = null;
            appId = (String) Context.getRequest().getSession().getAttribute("appId");
            if(appId == null){
                for (Cookie cookie:Context.getRequest().getCookies()){
                    if(cookie.getName().equals("CLIENT_APP_ID")){
                        appId = cookie.getValue();
                    }
                }
            }
            String redirectUrl = "/client/login?appId="+appId;
            Context.getResponse().sendRedirect(redirectUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean after() {
        return true;
    }

    @Override
    public void finish() {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
